﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using OhioState.Tiling;
using UnityEngine;

namespace OhioState.Tiling
{
    public class SpriteTilingGenerator : MonoBehaviour
    {
        public void GenerateTiling(Func<float, float> curve, float tileWidth, float tileHeight, int numberOfHorizontalTiles, float aspectRatio, float xMin, float xMax, float spriteSpacing)
        {
            SpriteTileSetBuilder tileSetBuilder = new SpriteTileSetBuilder((int)tileWidth, (int)tileHeight);
            tileSet = tileSetBuilder.Build() as SpriteTileSet;
            SpriteTilingBuilder tilingBuilder = new SpriteTilingBuilder(tileSet, curve, numberOfHorizontalTiles, aspectRatio, xMin, xMax);
            tiling = tilingBuilder.BuildTiling() as SpriteTiling;
            scaleHoriz = (spriteScale + spriteSpacing) * tileWidth;
            scaleVert = (spriteScale + spriteSpacing) * tileHeight;

            CreateTiling(spriteSpacing);
        }
        private void CreateTiling(float spriteSpacing)
        {
            spriteTiles = new List<GameObject>();

            for (int i = 0; i < tiling.Width; i++)
            {
                for (int j = 0; j < tiling.Height; j++)
                {
                    if (tiling.GetTile(i, j) == null) continue;
                    GameObject tile = new GameObject();
                    tile.transform.position = new Vector3(i * scaleHoriz , j * scaleVert, zPosition);
                    tile.transform.parent = this.transform;
                    tile.AddComponent<SpriteRenderer>();
                    tile.GetComponent<SpriteRenderer>().sprite = tiling.GetTile(i, j).TileData;
                    spriteTiles.Add(tile);
                }
            }
        }

        private List<GameObject> spriteTiles;
        private SpriteTileSet tileSet;
        private SpriteTiling tiling;
        private float scaleHoriz;
        private float scaleVert;
        float spriteScale = 0.01f; // Unity Sprite scale


        public float zPosition { get; set; }
    }
}
